#!/bin/bash
#
# Copyright (c) Citrix Systems 2008. All rights reserved.
#
#     ./stress-tests number_of_tests vm_per_host master slave1 slave2 ... slaveN
#

if [ $# -le 2 ]; then 
   echo "Usage: $0 number_of_tests vm_per_host master [slave1 ... slaveN]"
   echo "You need debian-etch-<host>-<1..vm_per_host> VMs installed in each host of the pool (use ./provision-vm to set them up)."
   echo "${0} is a XenRT-like script. It performs: "
   echo "  for each VM, do sequentialy:"
   echo "    <number_of_tests> start/wait IP/shutdown"
   echo "    <number_of_tests> suspend/resume"
   echo "    <number_of_tests> reboot"
   echo "    <number_of_tests> live migrate"
   echo "    <number_of_tests> non-live migrate"
   exit 1
fi 

N=$1
VM_PER_HOST=$2

shift
shift
HOSTS=$@
MASTER=$1

XE="xe -u root -pw xenroot -s ${MASTER}"

wait_IP () {
    VM=$1
    UUID=`${XE} vm-list name-label=${VM} params=uuid --minimal`
    RC=1
    while [ ${RC} -ne 0 ]
    do
	sleep 2
	IP=`${XE} vm-param-get uuid=${UUID} param-name=networks param-key="0/ip" &> /dev/null`
	RC=$?
    done
}

start () {
    VM=$1
    
    ${XE} vm-start vm=${VM}
    wait_IP ${VM}
}

perform () {
    OP=$1
    VM=$2
    EXTRA=$3

    ${XE} vm-${OP} vm=${VM} $EXTRA
}

tests () {
    HOST=$1
    VM=$2

    echo "[${VM}] start/stop tests."
    START=$(date +%s)
    for i in `seq 1 ${N}`; do
	start ${VM};
	perform shutdown ${VM};
	CURR=$(date +%s);
	DIFF=$(( ${CURR} - ${START} ));
	echo "${i} ${DIFF}" >> ${VM}.start-shutdown.dat
    done

    echo "[${VM}] suspend/resume tests."
    start ${VM}
    START=$(date +%s)
    for i in `seq 1 ${N}`; do
	perform suspend ${VM}
	perform resume ${VM}
	CURR=$(date +%s);
	DIFF=$(( ${CURR} - ${START} ));
	echo "${i} ${DIFF}" >> ${VM}.suspend-resume.dat
    done

    echo "[${VM}] reboot tests."
    START=$(date +%s)
    for i in `seq 1 ${N}`; do
	perform reboot ${VM}
	CURR=$(date +%s);
	DIFF=$(( ${CURR} - ${START} ));
	echo "${i} ${DIFF}" >> ${VM}.reboot.dat
    done
    
    wait_IP ${VM}

    echo "[${VM}] live migrate tests."
    START=$(date +%s)
    for i in `seq 1 ${N}`; do
	perform migrate ${VM} "live=true host=${HOST}"
	CURR=$(date +%s);
	DIFF=$(( ${CURR} - ${START} ));
	echo "${i} ${DIFF}" >> ${VM}.live-migrate.dat
    done

    echo "[${VM}] non-live migrate tests."
    START=$(date +%s)
    for i in `seq 1 ${N}`; do
	perform migrate ${VM} "live=false host=${HOST}"
	CURR=$(date +%s);
	DIFF=$(( ${CURR} - ${START} ));
	echo "${i} ${DIFF}" >> ${VM}.non-live-migrate.dat
    done

     perform shutdown ${VM}
}

for HOST in ${HOSTS}; do
    for i in `seq 1 ${VM_PER_HOST}`; do 
	VM="debian-etch-${HOST}-$i"
	echo "Starting tests on ${VM}."
	tests ${HOST} ${VM} &
    done
done
